package sy.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import sy.pageModel.DataGrid;
import sy.pageModel.Member;
import sy.pageModel.OrderDoctor;
import sy.pageModel.OrderStay;
import sy.service.OrderStayServiceI;
import sy.util.DateTimeUtility;
import sy.util.DateUtil;
import sy.util.StringUtil;

@Service("orderStayService")
public class OrderStayServiceImpl extends BaseService implements OrderStayServiceI {

	
	@Override
	public DataGrid datagrid(OrderStay order) throws Exception {
		DataGrid dg = new DataGrid();
		String sql = "select count(*) from xj_order_home a, view_hy b where a.userid=b.vnumber";
		sql = addWhere(order, sql);
		System.out.println(sql);
		long total = template.queryForLong(sql);
		System.out.println(total);
		dg.setTotal(total);
		
		sql = "select a.id, userid, a.deptid, c.name as depts, h_type, counts, num_price, sum_price, sj_money, apptext, service_detail, sq_time, r_time, tf_time, state_home, a.typeid, p_count, xm, sjh, sfzh "
		      + "from xj_order_home a, view_hy b, p_info c where a.userid=b.vnumber and a.deptid=c.id";
		sql = addWhere(order, sql);
		sql = addOrderBy(order, sql);
		sql = addLimit(order, sql);
		System.out.println(sql);
		final List<OrderStay> orderList = new ArrayList<OrderStay>();
        template.query(sql, new RowCallbackHandler(){
            public void processRow(ResultSet rs) throws SQLException {
            	OrderStay order = new OrderStay();
                order.setId(rs.getString("id"));
                order.setOrderId(rs.getString("id"));
                order.setCardId(rs.getString("userid"));
                order.setHotelId(rs.getString("deptid"));
                order.setHotel(rs.getString("depts"));
                order.setRoomName(rs.getString("h_type"));
                order.setRoomCount(rs.getInt("counts"));
                order.setRoomFee(rs.getDouble("num_price"));
                order.setTotalFee(rs.getDouble("sum_price"));
                order.setActualFee(rs.getDouble("sj_money"));
                order.setUnit(rs.getString("apptext"));
                order.setServiceDetails(rs.getString("service_detail"));
                order.setCreateTime(rs.getString("sq_time"));
                order.setCheckinTime(rs.getString("r_time"));
                order.setCheckoutTime(rs.getString("tf_time"));
                order.setStatus(rs.getString("state_home"));
                order.setStayType(rs.getString("typeid"));
                order.setPersonCount(rs.getInt("p_count"));
                order.setName(rs.getString("xm"));
                order.setMobile(rs.getString("sjh"));
                order.setCid(rs.getString("sfzh"));
            	orderList.add(order);
            }});
		dg.setRows(orderList);		
		return dg;
	}
	
	@Override
	public DataGrid datagridForAccepted(OrderStay order) throws Exception {
		DataGrid dg = new DataGrid();
		String sql = "select count(*) from xj_order_home a, view_hy b where a.userid=b.vnumber and a.state_home='" + OrderDoctor.ORDER_STATUS_ID_ACCEPTED + "'";
		sql = addWhere(order, sql);
		System.out.println(sql);
		long total = template.queryForLong(sql);
		System.out.println(total);
		dg.setTotal(total);
		
		sql = "select a.id, userid, a.deptid, c.name as depts, h_type, counts, num_price, sum_price, sj_money, apptext, service_detail, sq_time, r_time, tf_time, state_home, a.typeid, p_count, xm, sjh, sfzh "
		      + "from xj_order_home a, view_hy b, p_info c where a.userid=b.vnumber and a.deptid=c.id and a.state_home='" + OrderDoctor.ORDER_STATUS_ID_ACCEPTED + "'";
		sql = addWhere(order, sql);
		sql = addOrderBy(order, sql);
		sql = addLimit(order, sql);
		System.out.println(sql);
		final List<OrderStay> orderList = new ArrayList<OrderStay>();
        template.query(sql, new RowCallbackHandler(){
            public void processRow(ResultSet rs) throws SQLException {
            	OrderStay order = new OrderStay();
                order.setId(rs.getString("id"));
                order.setOrderId(rs.getString("id"));
                order.setCardId(rs.getString("userid"));
                order.setHotelId(rs.getString("deptid"));
                order.setHotel(rs.getString("depts"));
                order.setRoomName(rs.getString("h_type"));
                order.setRoomCount(rs.getInt("counts"));
                order.setRoomFee(rs.getDouble("num_price"));
                order.setTotalFee(rs.getDouble("sum_price"));
                order.setActualFee(rs.getDouble("sj_money"));
                order.setUnit(rs.getString("apptext"));
                order.setServiceDetails(rs.getString("service_detail"));
                order.setCreateTime(rs.getString("sq_time"));
                order.setCheckinTime(rs.getString("r_time"));
                order.setCheckoutTime(rs.getString("tf_time"));
                order.setStatus(rs.getString("state_home"));
                order.setStayType(rs.getString("typeid"));
                order.setPersonCount(rs.getInt("p_count"));
                order.setName(rs.getString("xm"));
                order.setMobile(rs.getString("sjh"));
                order.setCid(rs.getString("sfzh"));
            	orderList.add(order);
            }});
		dg.setRows(orderList);		
		return dg;
	}
	
	private String addWhere(OrderStay order, String sql) {
		if(!StringUtil.isNullOrEmpty(order.getOrderId())) {
			sql += " and a.id like '%" + order.getOrderId() + "%'";
		}
		if(!StringUtil.isNullOrEmpty(order.getCardId())) {
			sql += " and userid like '%" + order.getCardId() + "%'";
		}
		if(!StringUtil.isNullOrEmpty(order.getName())) {
			sql += " and xm like '%" + order.getName() + "%'";
		}
		if(!StringUtil.isNullOrEmpty(order.getMobile())) {
			sql += " and sjh like '%" + order.getMobile() + "%'";
		}
		if(!StringUtil.isNullOrEmpty(order.getCreateTimeStart())) {
			sql += " and sq_time >= '" + order.getCreateTimeStart() + "'";
		}
		if(!StringUtil.isNullOrEmpty(order.getCreateTimeEnd())) {
			sql += " and sq_time <= '" + order.getCreateTimeEnd() + "'";
		}
		return sql;
	}
	
	private String addLimit(OrderStay order, String sql) {
		int fromRow = (order.getPage() - 1) * order.getRows();
	    sql += " limit " + fromRow + "," + order.getRows();
	    return sql;
	}
	
	private String addOrderBy(OrderStay order, String sql) {
		if (order.getSort() != null) {
			if("cardId".equals(order.getSort())) {
				order.setSort("userid");
			} else if("name".equals(order.getSort())) {
				order.setSort("convert(xm using gbk)");
			} else if("createTime".equals(order.getSort())) {
				order.setSort("sq_time");
			} else if("mobile".equals(order.getSort())) {
				order.setSort("sjh");
			} else if("orderId".equals(order.getSort())) {
				order.setSort("id");
			} else if("statusName".equals(order.getSort())) {
				order.setSort("state_home");
			} else if("cid".equals(order.getSort())) {
				order.setSort("sfzh");
			} else if("hotel".equals(order.getSort())) {
				order.setSort("depts");
			} else if("roomName".equals(order.getSort())) {
				order.setSort("h_type");
			} else if("checkinTime".equals(order.getSort())) {
				order.setSort("r_time");
			} else if("checkoutTime".equals(order.getSort())) {
				order.setSort("tf_time");
			} else if("stayTypeName".equals(order.getSort())) {
				order.setSort("typeid");
			} else if("roomCount".equals(order.getSort())) {
				order.setSort("counts");
			} else if("roomFee".equals(order.getSort())) {
				order.setSort("num_price");
			} else if("totalFee".equals(order.getSort())) {
				order.setSort("sum_price");
			}
			sql += " order by " + order.getSort() + " " + order.getOrder();
		}
		return sql;
	}
	
	@Override
	@Transactional
	public OrderStay add(OrderStay order) throws Exception {
		System.out.println(order);
		//得到入住天数
		int stayDays = 0;
		if(!"qita".equals(order.getRoomName())) {
			long betweenSeconds = DateTimeUtility.getBetweenSeconds(order.getCheckinTime(), order.getCheckoutTime());
			System.out.println(betweenSeconds);
		    if(betweenSeconds < 0) {
		    	throw new Exception("入住时间不能晚于退房时间！");
		    }
		    stayDays = Integer.parseInt(String.valueOf(betweenSeconds / 24 / 3600 + 1));
		    System.out.println(stayDays);
		    //得到房型价钱等信息
		    Map<String, Object> infoMap = getRoomInfo(order.getRoomName());
		    if(infoMap.isEmpty()) {
		    	throw new Exception("获取房型信息失败！");
		    }
		    
		    order.setRoomFee((Double)infoMap.get("price" + order.getMemberType()));
		    order.setUnit((String)infoMap.get("unit"));
		    order.setPersonCount((Integer)infoMap.get("personCount"));
		    order.setTotalFee(order.getRoomFee() * stayDays * order.getRoomCount());
		    order.setRoomName((String)infoMap.get("roomName"));
		    
	    } else {
	    	order.setRoomName("交通或其它");
	    }
		order.setStatus(OrderDoctor.ORDER_STATUS_ID_WAIT_ACCEPT);
	    
	    Date now = new Date();
	    order.setCreateTime(DateUtil.format(now));
	    String orderId = "F-" + order.getCardId() + "-" + DateUtil.format(now, "yyyyMMddHHmmss");
	    order.setOrderId(orderId);
	    order.setId(orderId);
	    
	    System.out.println(order);
	    
	    String sql = "insert into xj_order_home (id,userid,deptid,h_type,counts,num_price,sum_price,apptext,sq_time,r_time,tf_time,state_home,typeid,p_count) " + 
	             "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
	
		Object[] paras = new Object[] {
				  order.getId(),
				  order.getCardId(),
				  order.getHotelId(),
				  order.getRoomName(),
				  order.getRoomCount(),
				  order.getRoomFee(),
				  order.getTotalFee(),
				  order.getUnit(),
				  order.getCreateTime(),
				  order.getCheckinTime(),
				  order.getCheckoutTime(),
				  order.getStatus(),
				  order.getStayType(),
				  order.getPersonCount()
		};
		
		int affectRow = 0;
		try {
		    affectRow = template.update(sql, paras);
		} catch(Exception e) {
			e.printStackTrace();
			throw new RuntimeException("添加订单失败，请联系系统管理员！");
		}
		if(affectRow == 0) {
			throw new RuntimeException("添加订单失败，请联系系统管理员！");
		}
	
	    return order;
	}
	

	
	@Override
	public Map<String, String> getHotelsByType(String stayType) throws Exception {
		final Map<String, String> result = new LinkedHashMap<String, String>();
		String sql = "select id, name from p_info where mainid=?";
		System.out.println(sql);
		Object[] paras = new Object[] {
	        stayType
	    };
		template.query(sql, paras, new RowCallbackHandler(){
            public void processRow(ResultSet rs) throws SQLException {
            	result.put(rs.getString("id"), rs.getString("name"));
            }
        });
		return result;
	}
	
	@Override
	public Map<String, String> getRoomNamesByHotelId(String hotelId) throws Exception {
		final Map<String, String> result = new LinkedHashMap<String, String>();
		String sql = "select id, titles from p_info_proj where deptid=?";
		System.out.println(sql);
		Object[] paras = new Object[] {
				hotelId
	    };
		template.query(sql, paras, new RowCallbackHandler(){
            public void processRow(ResultSet rs) throws SQLException {
            	result.put(rs.getString("id"), rs.getString("titles"));
            }
        });
		return result;
	}
	
	private Map<String, Object> getRoomInfo(String roomId) throws Exception {
		final Map<String, Object> result = new HashMap<String, Object>();
		String sql = "select titles, units, price0, price1, wh_price, cj_price, rnums from p_info_proj where id=?";
		System.out.println(sql);
		Object[] paras = new Object[] {
				roomId
	    };
		template.query(sql, paras, new RowCallbackHandler() {
            public void processRow(ResultSet rs) throws SQLException {
            	result.put("roomName", rs.getString("titles"));
            	result.put("price" + Member.MEMBER_TYPE_ID_BASE, rs.getDouble("price1"));
            	result.put("price" + Member.MEMBER_TYPE_ID_MAINTAIN, rs.getDouble("wh_price"));
            	result.put("price" + Member.MEMBER_TYPE_ID_ADVANCE, rs.getDouble("cj_price"));
            	result.put("price" + Member.MEMBER_TYPE_ID_HONOR, rs.getDouble("wh_price"));
            	result.put("unit", rs.getString("units"));
            	result.put("personCount", rs.getInt("rnums"));
            }
        });
		return result;
	}
	
	@Override
	@Transactional
	public OrderStay addDetails(OrderStay order) throws Exception {
		int affectRow = 0;
		String sql = "update xj_order_home set sj_money=?,service_detail=?,state_home=?" 
		             + " where id=?";
		System.out.println(sql);
		Object[] paras = new Object[] {
		    order.getActualFee(),
		    order.getServiceDetails(),
		    order.getStatus(),
		    order.getOrderId()
		};
		try {
		    affectRow = template.update(sql, paras);
		} catch(Exception e) {
			e.printStackTrace();
			throw new RuntimeException("生成详单失败，请联系系统管理员！");
		}
		if(affectRow == 0) {
			throw new RuntimeException("订单记录不存在！");
		} else if(affectRow > 1) {
			throw new RuntimeException("存在多条订单记录，生成详单失败，请联系系统管理员！");
		}
		return order;
	}

	@Override
	@Transactional
	public OrderStay edit(OrderStay order) throws Exception {
		String sql = "update xj_order_home set sj_money=?,service_detail=?,state_home=? where id=?";
		System.out.println(sql);
		order.setStatus(orderStatus(order.getStatus()));
		Object[] paras = new Object[] {
				order.getActualFee(),
				order.getServiceDetails(),
				order.getStatus(),
				order.getOrderId()
		};
		editOrderBySql(sql,paras);
		updateMenber(order.getCardId(),order.getOrderId(),order.getActualFee(),order.getStatus());
		return order;
	}

	@Override
	@Transactional
	public OrderStay saveStay(OrderStay order) {
		String sql = "update xj_order_home set sj_money=?,service_detail=? where id=?";
		System.out.println(sql);
		order.setStatus(orderStatus(order.getStatus()));
		Object[] paras = new Object[] {
				order.getActualFee(),
				order.getServiceDetails(),
				order.getOrderId()
		};
		editOrderBySql(sql,paras);
		return order;
	}

	@Override
	@Transactional
	public OrderStay editStayStatus(OrderStay order) {
		String sql = "update xj_order_home set state_home=? where id=?";
		System.out.println(sql);
		order.setStatus(OrderDoctor.ORDER_STATUS_ID_CANCELLED);
		Object[] paras = new Object[] {
				order.getStatus(),
				order.getOrderId()
		};
		editOrderBySql(sql,paras);
		return order;
	}
}
